package logic

import (
	"context"
	"errors"
	"shop_srv/cathe"
	"shop_srv/models"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *shop.CartAddRequest) (*shop.CartAddResponse, error) {
	var err error
	var g models.Goods
	g.ID = uint(in.GoodsId)
	err = g.GetGoodsById()
	if err != nil {
		logx.Error("商品不存在", err)
		return nil, err
	}
	if g.Status == 0 {
		logx.Error("此商品未上架，禁止添加购物车")
		return nil, errors.New("此商品未上架，禁止添加购物车")
	}
	if g.Num < int(in.Num) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	if cathe.ExstixGoods(int(in.UserId), int(in.GoodsId)) {
		err = cathe.UpdateGoodsNum(int(in.UserId), int(in.GoodsId), int(in.Num))
	} else {
		getMap := map[string]interface{}{
			"userId":  in.UserId,
			"goodsId": in.GoodsId,
			"title":   g.Title,
			"image":   g.Image,
			"price":   g.Price,
			"num":     g.Num,
		}
		err = cathe.CartAdd(int(in.UserId), int(in.GoodsId), getMap)
	}

	if err != nil {
		logx.Error("添加购物车失败")
		return nil, err
	}

	return &shop.CartAddResponse{}, nil
}
